import threading
from hashlib import sha256
from PyQt5 import QtWidgets, QtCore
from res.ui.login import Ui_Form
from src.qobj.mainwnd import mainwnd
from src.qobj.waitwgt import waitwgt
from src.util.entity import *
from src.util.mydb2 import mysession, rd


class loginwgt(QtWidgets.QWidget):
    msg_info = QtCore.pyqtSignal(str, str)
    hide_me = QtCore.pyqtSignal()
    login_success = QtCore.pyqtSignal()

    def __init__(self) -> None:
        super().__init__()
        ui = Ui_Form()
        ui.setupUi(self)
        ui.pushButton_2.clicked.connect(self.forgotpw)
        ui.pushButton.clicked.connect(self.login)
        self.ui = ui
        self.msg_info.connect(self.msgbox)
        self.wait = waitwgt("正在登录")
        self.hide_me.connect(self.hide_waiting)
        self.login_success.connect(self.to_main_window)
        self.ui.tno_edit.returnPressed.connect(self.login)
        self.ui.pass_edit.returnPressed.connect(self.login)

    def login(self) -> None:
        ui = self.ui
        usr = ui.tno_edit.text()
        pw = sha256(ui.pass_edit.text().encode("utf-8")).hexdigest()

        self.wait.show()
        thr = threading.Thread(target=self.thread_query, args=(usr, pw))
        thr.start()

    def thread_query(self, usr, passwd):
        try:
            ok = rd.get(f"{usr}+{passwd}")
            if ok:
                print("Redis 查询成功")
                rd.set(f"{usr}+{passwd}", "ok")
                self.login_success.emit()
                self.hide_me.emit()
                return
            print("Redis 查询失败")
        except:
            print("Redis 连接失败")

        try:
            print(f"用户={usr}, 密码={passwd}")
            cnt = mysession.query(班主任).filter(班主任.教师号 == usr,
                班主任.系统密码 == passwd).count()
            if cnt != 1:
                self.msg_info.emit("登录失败", "请检查教师号和密码")
                print("登录失败，请检查教师号和密码")
            else:
                print("登录成功")
                self.login_success.emit()
                try:
                    rd.set(f"{usr}+{passwd}", "ok")
                    print("Redis 写入成功")
                except:
                    print("Redis 写入失败")

        except:
            self.msg_info.emit("连接失败", "服务器连接失败，请稍后再试")
            print("数据库连接失败")
        self.hide_me.emit()

    def msgbox(self, title:str, msg:str) -> None:
        """展示提示框"""
        QtWidgets.QMessageBox.information(self, title, msg)

    def hide_waiting(self) -> None:
        self.wait.close()

    def forgotpw(self) -> None:
        self.msgbox("忘记密码", "请联系系统管理员修改密码")

    def to_main_window(self):
        self.hide()
        self.mainwnd = mainwnd(self.ui.tno_edit.text())
        self.mainwnd.show()
